package com.hz.framework.xml;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;
import com.hz.framework.util.CommonUtils;
import com.hz.framework.util.DateUtil;

import java.io.*;

import javax.servlet.http.HttpServletRequest;

//类 File 中的方法：
//String getAbsolutePath() 
//： 返回抽象路径名的绝对路径名字符串。 
//String   path= getServletContext().getRealPath("/"); 

public class Operatexml {
	
	public static void main(String[] args) {
		String xmlvalue="";
		String urls="E:\\apache-tomcat-7.0.2\\webapps\\pressystem\\workflow\\htmlxml\\hlj20110323135155828340800822html.xml";
		SAXBuilder builder = new SAXBuilder();
		InputStream file;
		try {
			file = new FileInputStream(urls);
			Document document = builder.build(file);//获得文档对象
			Element root = document.getRootElement();//获得根节点
			xmlvalue=root.getValue();
			file.close();
			CommonUtils.deBug(xmlvalue);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
    }
	public String XmlReadValue(String place,HttpServletRequest request) throws JDOMException, IOException {
		String xmlvalue="";
		String FlowId=request.getParameter("FlowId");
		String path=request.getRealPath("\\"); //获得当前文件夹路径 
		String url =path + "workflow\\htmlxml\\"+FlowId+".xml";
		SAXBuilder builder = new SAXBuilder();
		InputStream file = new FileInputStream(url);
		Document document = builder.build(file);//获得文档对象
		Element root = document.getRootElement();//获得根节点
		
		xmlvalue=root.getDocument().toString();
		file.close();
		return xmlvalue;
	}
	
	public String XmladdValue(HttpServletRequest request) throws JDOMException, IOException {
		
		String xmlvalue="";
		String FlowXML=request.getParameter("FlowXMLNew");
		String FlowId=request.getParameter("FlowId");
		StringBuffer  strXML=new StringBuffer ("<?xml version='1.0' encoding='UTF-8'?>");
		strXML.append("<html><![CDATA[  ");
		strXML.append(FlowXML);
		strXML.append("  ]]></html>");
		//out.print(strXML); 
		try{ 
		String xml=new String(strXML); 
		String path=request.getRealPath("\\"); //获得当前文件夹路径 
		String url =path + "webflow\\htmlxml\\"+FlowId+".xml";
		FileWriter fw=new FileWriter(url);//建立FileWriter对象，并实例化fw 
		//将字符串写入文件 
		fw.write(xml,0,xml.length()); //把XML文档写入文件  
		fw.close();
		String urls="E:\\workspace\\DZJCWeb\\WebRoot\\webflow\\htmlxml\\"+FlowId+".xml";
		FileWriter fws=new FileWriter(urls);//建立FileWriter对象，并实例化fw 
		fws.write(xml,0,xml.length()); //把XML文档写入文件  
		fws.close();
		//FlowDataSave  flowdatasave =new FlowDataSave();
		//isFinshed=flowdatasave.FlowSave(url,FlowId);
		} 
		catch(IOException e){ 
			CommonUtils.deBug("保存代码失败"); 
			e.printStackTrace();
		}
		return xmlvalue;
	}
	
	public boolean Xmldelete(HttpServletRequest request) throws JDOMException, IOException {
		
		boolean xmlvalue=true;
		String FlowId=request.getParameter("FlowId");
		try{ 
			String path=request.getRealPath("\\"); //获得当前文件夹路径 
			String url =path + "webflow\\htmlxml\\"+FlowId+".xml";
			File ff=new File(url);
			ff.delete();
			String urls="E:\\workspace\\DZJCWeb\\WebRoot\\webflow\\htmlxml\\"+FlowId+".xml";
			File fws=new File(urls);//建立FileWriter对象，并实例化fw 
			fws.delete();
			xmlvalue=true;
		} 
		catch(Exception e){ 
			CommonUtils.deBug("删除文件失败"); 
			e.printStackTrace();
			xmlvalue=false;
		}
		return xmlvalue;
	}
	
	 //////////改进的方法
	public List XmlRead(String place) throws JDOMException, IOException {
		SAXBuilder builder = new SAXBuilder();
		InputStream file = new FileInputStream("E:\\workspace\\HFITERP\\item\\"+place);
		Document document = builder.build(file);//获得文档对象
		Element root = document.getRootElement();//获得根节点
		List<Element> list = root.getChildren();
		List<Map<String, String>> xmllist = new ArrayList<Map<String, String>>();
		for(Element e:list) {
			Map<String, String> map = new HashMap<String, String>();
			map.put("id", e.getAttributeValue("id"));
			map.put("client", e.getChildText("client"));
			map.put("title", e.getChildText("title"));
			map.put("content", e.getChildText("content"));
			map.put("url", e.getChildText("url"));
			map.put("time", e.getChildText("time"));
			xmllist.add(map);
		}
		return xmllist;
	}
	
	public List XmlRead2(String place) throws JDOMException, IOException {
		SAXBuilder builder = new SAXBuilder();
		InputStream file = new FileInputStream("E:\\workspace\\HFITERP\\item\\"+place);
		Document document = builder.build(file);//获得文档对象
		Element root = document.getRootElement();//获得根节点
		List<Element> list = root.getChildren();
		List<Map<String, String>> xmllist = new ArrayList<Map<String, String>>();
		for(Element e:list) {
			Map<String, String> map = new HashMap<String, String>();
			map.put("id", e.getAttributeValue("id"));
			//CommonUtils.deBug(e.getContent(0).toString()+e.getContent(1).toString()+e.getContent(2).toString());
			map.put("pictureurl", e.getChildText("pictureurl"));
//			map.put("title", e.getChildText("title"));
//			map.put("content", e.getChildText("content"));
//			map.put("time", e.getChildText("time"));
			xmllist.add(map);
		}
		return xmllist;
	}
	public List AddXml(String xid,String client,String title,String content,String place,String weburl,String pictureurl ) throws JDOMException, FileNotFoundException, IOException {
		  
		  SAXBuilder builder = new SAXBuilder();
		  String time=DateUtil.getTime();
		  Document doc = builder.build("E:\\workspace\\HFITERP\\item\\"+place);//获得文档对象
		  Element root = doc.getRootElement();//获得根节点
		  if("".equals(xid)){
			  //控制队xml的写入
			  List<Element> list = root.getChildren();
			  int s=0;
			  for(Element e:list) {
				  if(Integer.parseInt(e.getAttributeValue("id")==""?"0":e.getAttributeValue("id"))>s){
					  s=Integer.parseInt(e.getAttributeValue("id"));
				  }
			  }
			  //添加新元素
			  Element element = new Element("person");
			  element.setAttribute("id", String.valueOf(s+1));
			  
			  Element element1 = new Element("client");
			  element1.setText(client);
			  Element element2 = new Element("title");
			  element2.setText(title);
			  Element element3 = new Element("content");
			  element3.setText(content);
			  Element element4 = new Element("url");
			  element4.setText(weburl);
			  Element element5 = new Element("time");
			  element5.setText(time);
			  
			  element.addContent(element1);
			  element.addContent(element2);
			  element.addContent(element3);
			  element.addContent(element4);
			  element.addContent(element5);
			  root.addContent(element);
			  doc.setRootElement(root);
			  //对数据的插入
			  CommonUtils.deBug(pictureurl.replace("\\", "\\\\"));
			  String xmlurl="E:\\workspace\\HFITERP\\item\\"+place;
			  String sql="insert into news_release (xmlurl,xmlid,client,title,content,weburl,pictureurl,time,place)values('"+xmlurl.replace("\\", "\\\\")+"','"+String.valueOf(s+1)+"','"+client+"','"+title+"','"+content+"','"+weburl+"','"+pictureurl.replace("\\", "\\\\")+"','"+time+"','"+place+"')";
			  //updateSql(sql);
			  //OperatePicture op=new OperatePicture();
//			  s_pic(大图片路径,生成小图片路径,大图片文件名,生成小图片文名,生成小图片宽度,生成小图片高度)；
			  //op.s_pic("E:\\workspace\\HFITERP\\images\\productbig","E:\\workspace\\HFITERP\\images\\productsmall",String   InputFileName,String   OutputFileName,int   width,int   height);
		  }else{
			  InputStream file = new FileInputStream("E:\\workspace\\HFITERP\\item\\po.xml");
			  doc = builder.build(file);//获得文档对象
			  List<Element> list = root.getChildren();
			  for(Element e:list) {
			   //获取ID值
			   if(Integer.parseInt(e.getAttributeValue("id"))==Integer.parseInt(xid)) {
			    CommonUtils.deBug("--------------------");
			    e.getChild("client").setText(client);
			    e.getChild("title").setText(title);
			    e.getChild("content").setText(content);
			    e.getChild("time").setText(time);
			    
			   }
			  }
			  String sql="update news_release set client='"+client+"',title='"+title+"',content='"+content+"',weburl='"+weburl+"',pictureurl='"+pictureurl+"',time='"+time+"' where xmlid='"+xid+"' and place='"+place+"'";
			  //updateSql(sql);
		  }
		  //文件处理
		  XMLOutputter out = new XMLOutputter();
		  out.output(doc, new FileOutputStream("E:\\workspace\\HFITERP\\item\\"+place));
		  
		  return XmlRead(place);
	}
	
	public List DelPerson(String id,String place) throws JDOMException, IOException {
			CommonUtils.deBug(id);
		  SAXBuilder builder = new SAXBuilder();
		  InputStream file = new FileInputStream("E:\\workspace\\HFITERP\\item\\"+place);
		  Document doc = builder.build(file);//获得文档对象
		  Element root = doc.getRootElement();//获得根节点
		  List<Element> list = root.getChildren();
		  for(Element e:list) {
		   //获取ID值
				 if(Integer.parseInt(e.getAttributeValue("id"))==Integer.parseInt(id)) {
				    root.removeContent(e);
				    break;
				 }
		  }
		  String sql="delete from news_release where xmlid='"+id+"' and place='"+place+"'";
		  //updateSql(sql);
//		  int i=1;
//		  for(Element e:list) {
//		   //获取ID值
//			  e.setAttribute("id", String.valueOf(i));
//			  i++;
//		  }
		  //文件处理
		  XMLOutputter out = new XMLOutputter();
		  out.output(doc, new FileOutputStream("E:\\workspace\\HFITERP\\item\\"+place));
		  return XmlRead(place);
	}
	
	public String mains(String src,String lanmu,String biaoti,String guanjianzi,String zuozhe,String laiyuan,String lianjie,String tupian,String zhaiyao,String neirong) throws IOException {
			  String time=DateUtil.getTime();
			 String fileurl="e:/workspace/HFITERP/time/"+time;
			File java = new File(fileurl); //生成目录路径
			java.mkdir(); //生成目录方法

			CommonUtils.deBug(src);
		   String fileame="";  
		   String title = "";
//		   String content = "小样，还搞不定你?";
//		   String editer = "秋水";
		   //模板路径
		   String filePath = src;
		   System.out.print(filePath);
		   String templateContent = "";
		try {
		   FileInputStream fileinputstream = new FileInputStream(filePath);// 读取模板文件
		   int lenght = fileinputstream.available();
		   byte bytes[] = new byte[lenght];
		   fileinputstream.read(bytes);
		   fileinputstream.close();
		   templateContent = new String(bytes);
		   
		   //System.out.print(templateContent); //未修改之前
		   templateContent = templateContent.replaceAll("##lanmu##",lanmu);
		   templateContent = templateContent.replaceAll("##biaoti##",biaoti);
		   templateContent = templateContent.replaceAll("##guanjianzi##",guanjianzi);
		   templateContent = templateContent.replaceAll("##zuozhe##",zuozhe);
		   templateContent = templateContent.replaceAll("##laiyuan##",laiyuan);
		   templateContent = templateContent.replaceAll("##lianjie##",lianjie);
		   templateContent = templateContent.replaceAll("##tupian##",tupian);
		   templateContent = templateContent.replaceAll("##zhaiyao##",zhaiyao);
		   templateContent = templateContent.replaceAll("##neirong##",neirong);// 替换掉模板中相应的地方
		   //System.out.print(templateContent); //修改之后
		
		   // 根据时间得文件名
		   Calendar calendar = Calendar.getInstance();
		   fileame = String.valueOf(calendar.getTimeInMillis()) + ".html";
		   title=fileame;
		   fileame = fileurl+"/"+ fileame;// 生成的html文件保存路径。
		   FileOutputStream fileoutputstream = new FileOutputStream(fileame);// 建立文件输出流
		   System.out.print("文件输出路径:");
		   System.out.print(fileame);
		   
		   byte tag_bytes[] = templateContent.getBytes();
		   fileoutputstream.write(tag_bytes);
		   fileoutputstream.close();
		} catch (Exception e) {
		   System.out.print(e.toString());
		}
		return time+"/"+title;
	}
	
	
	
	
	 //解析xml文件
	public static String XmlParse() throws JDOMException, IOException {
  	  SAXBuilder builder = new SAXBuilder();
  	  InputStream file = new FileInputStream("E:\\workspace\\HFITERP\\item\\po.xml");
  	  Document document = builder.build(file);//获得文档对象
  	  Element root = document.getRootElement();//获得根节点
  	  List<Element> list = root.getChildren();
  	  String xml="";
  	  for(Element e:list) {
  		  xml+=e.getAttributeValue("id")+e.getChildText("username")+e.getChildText("password")+"@@@@@";
  	   CommonUtils.deBug("ID="+e.getAttributeValue("id"));
  	   CommonUtils.deBug("username="+e.getChildText("username"));
  	   CommonUtils.deBug("password="+e.getChildText("password"));
  	  }
  	  return xml;
	 }
	
	 //增
	 public static void addXml() throws JDOMException, FileNotFoundException, IOException {
	  SAXBuilder builder = new SAXBuilder();
	  Document doc = builder.build("E:\\workspace\\HFITERP\\item\\po.xml");//获得文档对象
	  Element root = doc.getRootElement();//获得根节点
	  
	  //添加新元素
	  Element element = new Element("person");
	  element.setAttribute("id", "3");
	  Element element1 = new Element("username");
	  element1.setText("hanfei");
	  Element element2 = new Element("password");
	  element2.setText("27078025");
	  element.addContent(element1);
	  element.addContent(element2);
	  root.addContent(element);
	  doc.setRootElement(root);
	  
	  //文件处理
	  XMLOutputter out = new XMLOutputter();
	  out.output(doc, new FileOutputStream("E:\\workspace\\HFITERP\\item\\po.xml"));
	 }
	 
	 //根据ID值删除一个节点 
	 public static void deletePerson(int id) throws JDOMException, IOException {
	  SAXBuilder builder = new SAXBuilder();
	  InputStream file = new FileInputStream("E:\\workspace\\HFITERP\\item\\po.xml");
	  Document doc = builder.build(file);//获得文档对象
	  Element root = doc.getRootElement();//获得根节点
	  List<Element> list = root.getChildren();
	  for(Element e:list) {
	   //获取ID值
	   if(Integer.parseInt(e.getAttributeValue("id"))==id) {
	    root.removeContent(e);
	    break;//??
	   }
	  }
	  
	  //文件处理
	  XMLOutputter out = new XMLOutputter();
	  out.output(doc, new FileOutputStream("E:\\workspace\\HFITERP\\item\\po.xml"));
	 }
	 
	 //根据ID值修改一个节点 
	 public static void updatePerson(int id) throws JDOMException, IOException {
	  SAXBuilder builder = new SAXBuilder();
	  InputStream file = new FileInputStream("E:\\workspace\\HFITERP\\item\\po.xml");
	  Document doc = builder.build(file);//获得文档对象
	  Element root = doc.getRootElement();//获得根节点
	  List<Element> list = root.getChildren();
	  for(Element e:list) {
	   //获取ID值
	   if(Integer.parseInt(e.getAttributeValue("id"))==id) {
	    CommonUtils.deBug("--------------------");
	    e.getChild("username").setText("huaxiqfl");
	    e.getChild("password").setText("mamama");
	    
	   }
	  }
	  
	  //文件处理
	  XMLOutputter out = new XMLOutputter();
	  out.output(doc, new FileOutputStream("E:\\workspace\\HFITERP\\item\\po.xml"));
	 }

}
